import { notFound } from 'next/navigation'
import { Metadata } from 'next'
import { readFile } from 'fs/promises'
import { join } from 'path'
import { getAllDocSlugs } from '@/app/data/docs-nav'
import { getDocMarkdown } from '@/app/lib/mdx-to-markdown'
import { DocsMarkdownProvider } from '@/app/components/docs/DocsMarkdownContext'

// Map of slugs to their MDX content imports
const docsContent: Record<string, () => Promise<{ default: React.ComponentType }>> = {
    'introduction': () => import('@/content/docs/introduction.mdx'),
    'quick-start': () => import('@/content/docs/quick-start.mdx'),
    'permissions': () => import('@/content/docs/permissions.mdx'),
    'verification': () => import('@/content/docs/verification.mdx'),
    'lexicons/publication': () => import('@/content/docs/lexicons/publication.mdx'),
    'lexicons/document': () => import('@/content/docs/lexicons/document.mdx'),
    'lexicons/subscription': () => import('@/content/docs/lexicons/subscription.mdx'),
    'lexicons/theme': () => import('@/content/docs/lexicons/theme.mdx'),
    'implementations': () => import('@/content/docs/implementations.mdx'),
    'faq': () => import('@/content/docs/faq.mdx'),
}

async function getFrontmatter(slugPath: string): Promise<{ title?: string; description?: string; ogImage?: string; atUri?: string }> {
    const filePath = join(process.cwd(), 'content', 'docs', `${slugPath}.mdx`)
    const raw = await readFile(filePath, 'utf-8')

    const match = raw.match(/^---\n([\s\S]*?)\n---/)
    if (!match) return {}

    const frontmatter: Record<string, string> = {}
    for (const line of match[1].split('\n')) {
        const [key, ...rest] = line.split(':')
        if (key && rest.length) {
            frontmatter[key.trim()] = rest.join(':').trim().replace(/^["']|["']$/g, '')
        }
    }

    return frontmatter
}

// Generate static params for all doc pages
export function generateStaticParams() {
    return getAllDocSlugs().map((slug) => ({ slug }))
}

export async function generateMetadata({
    params,
}: {
    params: Promise<{ slug: string[] }>
}): Promise<Metadata> {
    const { slug } = await params
    const slugPath = slug.join('/')

    if (!docsContent[slugPath]) return {}

    const { title, description, ogImage } = await getFrontmatter(slugPath)

    return {
        title: title ? `${title} - Standard.site` : undefined,
        description,
        openGraph: {
            title: title ? `${title} - Standard.site` : undefined,
            description,
            images: ogImage ? [`/media/${ogImage}`] : undefined,
        },
    }
}

export default async function DocPage({
    params,
}: {
    params: Promise<{ slug: string[] }>
}) {
    const { slug } = await params
    const slugPath = slug.join('/')

    const loader = docsContent[slugPath]
    if (!loader) {
        notFound()
    }

    const [{ default: Content }, markdown, { atUri }] = await Promise.all([
        loader(),
        getDocMarkdown(slugPath),
        getFrontmatter(slugPath),
    ])

    return (
        <DocsMarkdownProvider markdown={markdown} atUri={atUri}>
            <Content />
        </DocsMarkdownProvider>
    )
}
